package com.dynamicthreadpool.netty.server;

import com.dynamicthreadpool.netty.handler.ThreadPoolControlHandler;
import com.dynamicthreadpool.netty.protocol.ThreadPoolMessageDecoder;
import com.dynamicthreadpool.netty.protocol.ThreadPoolMessageEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 线程池控制服务器，基于Netty实现
 * 提供线程池的远程控制功能
 */
public class ThreadPoolControlServer {
    
    private final int port;
    private final String accessToken;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ChannelFuture serverChannelFuture;
    
    /**
     * 构造函数，使用默认的空accessToken
     * @param port 端口号
     */
    public ThreadPoolControlServer(int port) {
        this(port, null);
    }
    
    /**
     * 构造函数
     * @param port 端口号
     * @param accessToken 访问令牌，用于身份验证
     */
    public ThreadPoolControlServer(int port, String accessToken) {
        this.port = port;
        this.accessToken = accessToken;
    }
    
    public void start() throws Exception {
        // 创建两个线程组：bossGroup处理客户端连接，workerGroup处理客户端读写
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        
        try {
            // 创建服务器启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            
            // 配置服务器启动参数
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)  // 使用NIO的服务器通道
                    .option(ChannelOption.SO_BACKLOG, 128)  // 设置等待队列大小
                    .childOption(ChannelOption.SO_KEEPALIVE, true)  // 保持连接活跃
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加处理器到管道
                            ch.pipeline()
                                    .addLast(new ThreadPoolMessageDecoder())
                                    .addLast(new ThreadPoolMessageEncoder())
                                    .addLast(new ThreadPoolControlHandler(accessToken));
                        }
                    });
            
            // 绑定端口，同步等待成功
            System.out.println("Thread Pool Control Server starting on port " + port);
            serverChannelFuture = bootstrap.bind(port).sync();
            
            // 等待服务关闭
            serverChannelFuture.channel().closeFuture().sync();
        } finally {
            // 优雅关闭线程组
            shutdown();
        }
    }
    
    /**
     * 停止服务器
     */
    public void shutdown() {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        System.out.println("Thread Pool Control Server stopped");
    }
    
    /**
     * 优雅关闭服务器
     */
    public void stop() {
        if (serverChannelFuture != null && serverChannelFuture.channel().isActive()) {
            serverChannelFuture.channel().close();
        }
    }
    
    public static void main(String[] args) throws Exception {
        int port = 8888;
        String accessToken = null;
        
        if (args.length > 0) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                System.err.println("Invalid port number, using default: " + port);
            }
        }
        
        if (args.length > 1) {
            accessToken = args[1];
        }
        
        ThreadPoolControlServer server = new ThreadPoolControlServer(port, accessToken);
        server.start();
    }
}